package top.meijhm.communitymanagement.common.auth.filter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import top.meijhm.communitymanagement.common.auth.handler.LoginFailureHandler;
import top.meijhm.communitymanagement.common.exceptions.CaptchaException;
import top.meijhm.communitymanagement.common.redis.RedisUtil;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CaptchaFilter extends OncePerRequestFilter {
    @Autowired
    RedisUtil redisUtil;

    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    LoginFailureHandler loginFailureHandler;

    // 校验验证码逻辑
    private void validate(HttpServletRequest request) throws AuthenticationException {
        String code = request.getParameter("code");
        String key = request.getParameter("userKey");
        if (StringUtils.isBlank(code) || StringUtils.isBlank(key)) {
            throw new CaptchaException("验证码错误");
        }

        if (!code.equals(redisUtil.get(key))) {
            throw new CaptchaException("验证码错误");
        }
        // 若验证码正确，执行以下语句
        // 一次性使用
        redisUtil.delete(key);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String url = request.getRequestURI();
        if ("/login/auth".equals(url) && request.getMethod().equals("POST")) {
            // 校验验证码
            try {
                validate(request);
            } catch (CaptchaException e) {
                // 交给认证失败处理器
                loginFailureHandler.onAuthenticationFailure(request, response, e);
            }
        }
        filterChain.doFilter(request, response);
    }
}